<html>
	<body>
		<script type="text/javascript">
			var extensionEnabled;

			// Converts a string to a boolean value
			function toBool(str) {
				return "false" === str ? false : true;
			}
			
			// Dynamically load jQuery
			function loadJQuery(callback) {
				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function(data) {
					if (xhr.readyState == 4) {
						if (xhr.status == 200) {
							callback(xhr.responseText);
						} else {
							callback(null);
						}
					}
				}
				var url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
				xhr.open('GET', url, true);
				xhr.send();
			};

			function onRequest(request, sender, callback) {
				switch(request.action) {
					case 'isExtensionEnabled':
						callback(extensionEnabled);
						break;
					case 'loadJQuery':
						loadJQuery(callback);
						break;
				}
			};
			
			function refreshBrowserActionIcon() {
				if (extensionEnabled) {
					chrome.browserAction.setIcon({path: 'images/icon19.png'});
					chrome.browserAction.setTitle({title: 'Hover Zoom\nClick to disable automatic image zooming'});
				} else {
					chrome.browserAction.setIcon({path: 'images/icon19d.png'});
					chrome.browserAction.setTitle({title: 'Hover Zoom\nClick to enable automatic image zooming'});
				}
			}

			function init() {
			
				// Load state
				// If none exists, create one
				if (localStorage.extensionEnabled == null)
					localStorage.extensionEnabled = true;
					
				extensionEnabled = toBool(localStorage.extensionEnabled);
				
				refreshBrowserActionIcon();
						
				chrome.extension.onRequest.addListener(onRequest);
				
				chrome.browserAction.onClicked.addListener(function(tab) {
				
					// Store new state
					localStorage.extensionEnabled = extensionEnabled = !extensionEnabled;
					refreshBrowserActionIcon();
					
					// Send new state to all tabs
					chrome.windows.getAll(null, function (windows) {
						for (i in windows) {
							chrome.tabs.getAllInWindow(windows[i].id, function(tabs) {
								for (j in tabs) {
									chrome.tabs.sendRequest(tabs[j].id, {action: 'extensionEnabledChanged', extensionEnabled: extensionEnabled});
								}
							});
						}
					});
					
				});
			}

			init();
		</script>
	</body>
</html>